<?php

require_rewrite(SYSTEM_PATH . 'config/union_config.php');
require_rewrite(SYSTEM_PATH . 'config/union_crypt_config.php');
//require_once(MODULE_PATH . 'union/union.class.php');

/**
 * 用户处理联盟用户信息数据，含CPS类型网站
 */
class Handler_union {

    /**
     * 根据unionId获取对应的联盟合作商的名字(域名)
     * @param <string> $union_id 联盟ID
     * @return <string>联盟合作商名字
     */
    public static function getUnionById($union_id) {
        $union_id = strtoupper(trim($union_id));
        //从缓存中获取值
        $data_key = 'union_domain_key_' . $union_id;
        $cache = MemoryCache::getInstance();
        $domain = $cache->get($data_key);
        //缓存没有则从配置中读取
        if (empty($domain)) {
            $union_config = self::getConfig();
            foreach ($union_config as $key => $value) {
                foreach ($value as $k => $v) {
                    if (strtoupper($v) == $union_id) {
                        $cache->set($data_key, $key, 172800); //60*60*24*2
                        return $key; //此处不能用break，否则外层循环还会继续执行
                    }
                }
            }
        }
        return $domain;
    }

    /**
     * 读取联盟配置，缓存12小时
     * @return <array> 联盟完整配置
     */
    private static function getConfig() {
        //从缓存中获取配置
        $key = 'union_config';
        $cache = MemoryCache::getInstance();
        $union_config = $cache->get($key);
        //缓存中若没有则从文件读取并在缓存中保存12小时
        if (empty($union_config)) {
            $union_config = Union_Config::$Union;
            $cache->set($key, $union_config, 43200); //60*60*12
        }
        return $union_config;
    }

    //在cookie中保存成果网相关信息
    public static function saveInfo_chenet() {
        $chanet_cps_sid = $_GET['chanet_cps_sid'];
        //不为空时才存cookie，以免被空值覆盖
        if (!empty($chanet_cps_sid)) {
            return Handler_http::setCookie("chanet_cps_sid", $chanet_cps_sid);
        }
        return false;
    }

    /**
     * 获取cookie中保存的成果网CPS信息
     * @return <array> 成果网CPS信息
     */
    public static function getInfo_chenet() {
        return Handler_http::getCookie('chanet_cps_sid');
    }

    /**
     * 获取cookie中保存的成果网CPS信息（以union标识为方法名）
     * @return <array> 成果网CPS信息
     */
    public static function getInfo_chahet() {
        return self::getInfo_chenet();
    }

    //在cookie中保存亿起发,亿玛相关信息
    public static function saveInfo_yiqifa() {
        $cid = $_GET['cid']; //推广标识
        $wi = $_GET['wi']; //下级网站信息
        //不为空时才存cookie，以免被空值覆盖
        if (!empty($cid) && !empty($wi)) {
            $yiqifa_cps_info = $cid . ';' . $wi;
            return Handler_http::setCookie('cps_yiqifa', $yiqifa_cps_info);
        }
        return false;
    }

    /**
     * 获取cookie中保存的亿起发的CPS信息
     * @return <string> 亿起发的CPS信息
     */
    public static function getInfo_yiqifa() {
        return Handler_http::getCookie('cps_yiqifa');
    }

    /**
     * 获取cookie中保存的亿起发的CPS信息（以union标识为方法名）
     * @return <string> 亿起发的CPS信息
     */
    public static function getInfo_eqifa() {
        return self::getInfo_yiqifa();
    }

    /**
     * 获取cookie中保存的领克特的CPS信息
     * @return <string> 领克特的CPS信息
     */
    public static function getInfo_linktech() {
        return Handler_http::getCookie('cps_linktech');
    }

    /**
     * 获取cookie中保存的领克特的CPS信息（以union标识为方法名）
     * @return <string> 领克特的CPS信息
     */
    public static function getInfo_lingkete() {
        return self::getInfo_linktech();
    }

    /**
     * 获取cookie中保存的唯一传媒的CPS信息
     * @return <array> 唯一传媒的CPS信息
     */
    public static function getInfo_weiyi() {
        return Handler_http::getCookie('cps_weiyi');
    }

    /**
     * 获取cookie中保存的艾德思奇网盟的CPS信息
     * @return <array> 唯一传媒的CPS信息
     */
    public static function getInfo_pubsage() {
        return Handler_http::getCookie('pubsage_cps_sid');
    }

    /**
     * 获取cookie中保存的多麦的CPS信息
     * @return <array> 多麦的CPS信息
     */
    public static function getInfo_duomai() {
        return Handler_http::getCookie('duomai_cps_euid');
    }

    /**
     * 获取cookie中保存的游比比的CPS信息
     * @return <array> 游比比的CPS信息
     */
    public static function getInfo_youbibi(){
    	return Handler_http::getCookie('youbibi_cps_euid');
    }
    
    /**
     * 获取cookie中保存的中视网盟的CPS信息
     * @return string 中视网盟的CPS信息
     */
    public static function getInfo_zswm() {
        //获取cookie信息，cookie在webroot/cps/cps_weiyi.php下生成
        return Handler_http::getCookie('cps_zswm');
    }

    /**
     * 获取cookie中保存的中视网盟的CPS信息（以union标识为方法名）
     * @return string 中视网盟的CPS信息
     */
    public static function getInfo_ctvwm() {
        return self::getInfo_zswm();
    }

    /**
     * 获取cookie中保存的艾德思奇网盟的CPS信息
     * @return string 艾德思奇网盟的CPS信息
     */
    public static function saveInfo_pubsage() {
        $pubsage_cps_sid = $_GET['sid'];
        //不为空时才存cookie，以免被空值覆盖
        if (!empty($pubsage_cps_sid)) {
            return Handler_http::setCookie("pubsage_cps_sid", $pubsage_cps_sid);
        }
        return false;
    }

    /**
     * 获取cookie中保存的多麦的CPS信息
     * @return string 多麦的CPS信息
     */
    public static function saveInfo_duomai() {
        $duomai_cps_euid = $_GET['euid'];
        //不为空时才存cookie，以免被空值覆盖
        if (!empty($duomai_cps_euid)) {
            return Handler_http::setCookie("duomai_cps_euid", $duomai_cps_euid);
        }
        return false;
    }
    
    /**
     * 获取cookie中保存的游比比的CPS信息
     * @return string 游比比的CPS信息
     */
    public static function saveInfo_youbibi(){
    	$youbibi_cps_euid = $_GET['track_code'];
    	//不为空时才存cookie，以免被空值覆盖
    	if( !empty($youbibi_cps_euid) ){
    		return Handler_http::setCookie("youbibi_cps_euid", $youbibi_cps_euid);
    	}
    	return false;
    }

    //获取union_id和channel_id的对应关系
    public static function getUnion_Channel($unionId = "") {
        if (array_key_exists($unionId, Union_Config::$Union_Channel)) {
            return Union_Config::$Union_Channel[$unionId];
        }
        return Union_Config::$Union_Channel["default"];
    }

    /**
     * 生成存储uid等联盟信息在memcache的key
     * @param <string> $uid 联盟ID
     * @return <string> 加密后的key值，如果uid为空，则返回空字符串
     */
    public static function generateCacheKeyForUid($uid) {
        if (!empty($uid)) {
            $key = CRYPT_PREFIX_KEY . time() . trim($uid);
            return Handler_string::generateCheckCode($key);
        }
        return '';
    }

    /**
     * 生成uid的校验码，用于对uid在客户端的key是否被篡改进行二次校验
     * @param <string> $uid 联盟ID
     * @return <string> 加密后的校验值，如果uid为空，则返回空字符串
     */
    public static function generateVerifyCodeForUid($uid) {
        if (!empty($uid)) {
            $key = CRYPT_PREFIX_KEY . trim($uid);
            return Handler_string::generateCheckCode($key);
        }
        return '';
    }

    /**
     * 获取uid在cookie中存储的key值
     */
    public static function getUidCookieKey() {
        return Union_Config::$Uid_Cookie_Key;
    }

    /**
     * 获取uid校验值在cooki中存储的key值
     */
    public static function getUidVerifyCookieKey() {
        return Union_Config::$Uid_Verify_Cookie_Key;
    }

    /**
     * 从cookie中获取当前的uid信息并进行校验码比对
     * 如果存在且通过校验返回uid，否则返回空字符串
     * @return <string> uid
     */
    public static function getCurrentUid() {
        //从cookie中获取缓存加密key
        $key = Handler_http::getCookie(Union_Config::$Uid_Cookie_Key);
        //如果加密的cookie不存在，则查看cookie中原规则的union_id是否存在，此逻辑为SEM和CPC保留
        if (empty($key)) {
            $uid_for_cps_sem = Handler_http::getCookie(UNIONID_COOKIE);
            return empty($uid_for_cps_sem) ? '' : $uid_for_cps_sem;
        }
        //根据key从缓存中获取uid
        $cache = MemoryCache::getInstance();
        $data = $cache->get($key);
        //不存在直接返回空字符串
        if (empty($data)) {
            return '';
        }
        $uid = $data['uid'];
        //从cookie中获取uid校验码
        $verify_code = Handler_http::getCookie(Union_Config::$Uid_Verify_Cookie_Key);
        $verify_code = substr($verify_code, 0, strpos($verify_code, ','));
        //不存在直接返回空字符串
        if (empty($verify_code)) {
            return '';
        }
        //为uid生成校验码
        $verify_txt = self::generateVerifyCodeForUid($uid);
        //如果2个校验码相同返回uid，否则返回空字符串
        return ($verify_txt == $verify_code) ? $uid : '';
    }

    /**
     * 在Cookie中设置uid缓存key
     * @param <string> $cachekey uid在memcache中的value
     * @return <bool> 设置成功返回true，否则false
     */
    private static function setMxCookie($cachekey) {
        if (empty($cachekey)) {
            return false;
        }
        $key = self::getUidCookieKey();
        return Handler_http::setCookie($key, $cachekey);
    }

    /**
     * 在cookie设置uid校验码
     * @param <string> $uid 联盟ID
     * @return <bool> 设置成功返回true，否则false
     */
    private static function setUxCookie($uid) {
        //获得加密后的值
        $key = self::getUidVerifyCookieKey();
        $value = self::generateVerifyCodeForUid($uid);
        //在校验码后追加明码uid，明码uid不作为程序取值使用，仅方便程序调试时查看
        $value .= ',' . $uid;
        return Handler_http::setCookie($key, $value);
    }

    /**
     * 将uid存入Memcache，key由内部逻辑生成
     * @param <string> $uid 联盟ID
     * @return <string> 在memcache中的key
     */
    private static function saveUidToCache($uid) {
        $key = self::generateCacheKeyForUid($uid);
        $uid = trim($uid);
        $data = array(
            'uid' => $uid
        );
        $cache = MemoryCache::getInstance();
        $cache->set($key, $data, 43200); //60*60*12
        return $key;
    }

    /**
     * 保存uid到memcache，同时设置相关cookie
     * @param <string> $uid 联盟ID
     * @return <bool> 设置成功返回true，否则false
     */
    public static function saveUid($uid) {
        if (empty($uid)) {
            return false;
        }
        $cachekey = self::saveUidToCache($uid);
        self::setMxCookie($cachekey);
        self::setUxCookie($uid);
        return true;
    }

    /**
     * 检测cookie中是否有uid信息相关的cookie都存在
     * @return <bool> 相关cookie都存在返回true，否则返回false
     */
    public static function isUidExistInCookie() {
        $mx = Handler_http::getCookie(Union_Config::$Uid_Cookie_Key);
        $ux = Handler_http::getCookie(Union_Config::$Uid_Verify_Cookie_Key);
        if (empty($mx) || empty($ux)) {
            return false;
        }
        return true;
    }

    /**
     * 删除uid相关的cookie
     */
    public static function deleteUidInCookie() {
        Handler_http::delCookie(Union_Config::$Uid_Cookie_Key);
        Handler_http::delCookie(Union_Config::$Uid_Verify_Cookie_Key);
        Handler_http::delCookie('union_id');
    }

    /**
     * 获取联合登录配置 
     * @param <string> $uid 联盟ID
     * @return <array> 对应的配置节，数组，包含多项信息
     */
    public static function getUnionLoginConfigByUid($uid) {
        if (!empty($uid)) {
            return Union_Config::$Union_Login[$uid];
        }
        return null;
    }

    /**
     * 获取联合登录信息在cookie中的key
     */
    public static function getUnionLoginCookieKey() {
        return Union_Config::$Union_Login_Cookie_Key;
    }

    /**
     * 将联合登录的信息存入Memcache，key由内部逻辑生成
     * @param <array> $unionLoginInfo 联合登录的信息
     * @return <string> 在memcache中的key
     */
    public static function saveUnionLoginToCache($unionLoginInfo) {
        $key = self::generateCacheKeyForUid($unionLoginInfo['aid'] . $unionLoginInfo['uid']);
        $cache = MemoryCache::getInstance();
        $cache->set($key, $unionLoginInfo, 43200); //60*60*12
        return $key;
    }

    /**
     * 从cookie中获取当前的联合登录的信息
     * 如果存在且通过校验返回数组，否则返回空
     * @return <array> $unionLoginInfo
     * 'aid' 媒体商唯一标示
     * 'uid'	媒体商提供的用户唯一标示
     * 'uname'	用户昵称
     * 'OpenId'	QQ彩贝专用CPS信息，其他媒体商为空
     * 'isTemp' 是否为临时会员，1为是0为不是
     */
    public static function getUnionLoginInfo() {
        //从cookie中获取缓存key
        $key = Handler_http::getCookie(Union_Config::$Union_Login_Cookie_Key);
        //不存在直接返回空字符串
        if (empty($key)) {
            return '';
        }
        //根据key从缓存中获取联合登录的信息
        $cache = MemoryCache::getInstance();
        $data = $cache->get($key);
        //不存在直接返回空字符串
        if (empty($data)) {
            return '';
        }
        return $data;
    }

    /**
     * 
     * 替换联合登录中的临时会员状态
     */
    public static function replaceUnionLoginInfoisTemp() {
        //从cookie中获取缓存key
        $key = Handler_http::getCookie(Union_Config::$Union_Login_Cookie_Key);
        if (empty($key)) {
            return false;
        }
        //根据key从缓存中获取联合登录的信息
        $cache = MemoryCache::getInstance();
        $data = $cache->get($key);
        if (empty($data)) {
            return false;
        }
        $newData = array();
        foreach ($data as $key => $value) {
            if ($key != 'isTemp') {
                $newData[$key] = $value;
            } else {
                $newData[$key] = 0;
            }
        }
        return $cache->replace($key, $newData, 43200);
    }

    /**
     * 
     * 获取qq联合登录配置
     */
    public static function getQQLoginConfig() {
        return Union_Config::$QQ_Login;
    }

    /**
     * 
     * 获取QQ登录地址
     */
    public static function getQQLoginUrl() {
        $qq_login_config = self::getQQLoginConfig();
        $state = md5(uniqid(rand(), TRUE));
        $memcacheKey = self::saveLoginSecretToCache($state);
        Handler_http::setCookie(Union_Config::$QQ_Login_Cookie_Key, $memcacheKey, 0);
        //拼接URL     
        $qqLoginUrl = $qq_login_config["CODEURL"]
                . "&client_id=" . $qq_login_config["APPID"]
                . "&redirect_uri=" . urlencode(HTTPURL . '/welcome/qq_login/')
                . "&state=" . $state;
        return $qqLoginUrl;
    }

    /**
     * 
     * 获取Alipay联合登录配置
     */
    public static function getAlipayLoginConfig() {
        return Union_Config::$Alipay_Login;
    }

    /**
     * 用于防钓鱼，调用接口query_timestamp来获取时间戳的处理函数
     * 注意：该功能PHP5环境及以上支持，因此必须服务器、本地电脑中装有支持DOMDocument、SSL的PHP配置环境。建议本地调试时使用PHP开发软件
     * return 时间戳字符串
     */
    private static function getAlipayTimeStamp() {
        $alipay_login_config = self::getAlipayLoginConfig();
        $url = $alipay_login_config["GETWAYURL"] . "?service=query_timestamp&partner=" . $alipay_login_config["PARTNER"];
        $encrypt_key = "";

        $doc = new DOMDocument();
        $doc->load($url);
        $itemEncrypt_key = $doc->getElementsByTagName("encrypt_key");
        $encrypt_key = $itemEncrypt_key->item(0)->nodeValue;

        return $encrypt_key;
    }

    /**
     * 生成支付宝签名结果
     * @param $para_temp 要签名的数组
     * return 签名结果字符串
     */
    public static function getAlipaySign($para_temp) {
        $alipay_login_config = self::getAlipayLoginConfig();

        //除去待签名参数数组中的空值和签名参数
        $para_filter = array();
        foreach ($para_temp as $key => $value) {
            if ($key == "sign" || $key == "sign_type" || $value == "")
                continue;
            else
                $para_filter[$key] = $para_temp[$key];
        }

        //对待签名参数数组排序
        ksort($para_filter);
        reset($para_filter);

        $arg = "";
        foreach ($para_filter as $key => $value) {
            $arg.=$key . "=" . $value . "&";
        }
        //去掉最后一个&字符
        $arg = substr($arg, 0, count($arg) - 2);

        //如果存在转义字符，那么去掉转义
        $arg = stripslashes($arg);

        $prestr = $arg . $alipay_login_config["KEY"];
        
        $sign = md5($prestr);
        return $sign;
    }

    /**
     * 
     * 获取Alipay登录地址
     */
    public static function getAlipayLoginUrl() {
        $alipay_login_config = self::getAlipayLoginConfig();
        //构造要请求的参数数组
        $parameter = array(
            "service" => "alipay.auth.authorize",
            "target_service" => 'user.auth.quick.login',
            "partner" => trim($alipay_login_config["PARTNER"]),
            "_input_charset" => trim(strtolower($alipay_login_config["INPUTCHARSET"])),
            "return_url" => HTTPURL . '/welcome/alipay_login/',
//	        "anti_phishing_key"	=> self::getAlipayTimeStamp(),
//			"exter_invoke_ip"	=> Handler_http::getIP(),

            "anti_phishing_key" => '',
            "exter_invoke_ip" => '',
        );

        $mysign = self::getAlipaySign($parameter);

        //签名结果与签名方式加入请求提交参数组中
        $parameter['sign'] = $mysign;
        $parameter['sign_type'] = strtoupper(trim($alipay_login_config['SIGNTYPE']));

        //拼接URL     
        $alipayLoginUrl = $alipay_login_config["GETWAYURL"] . "?";
        foreach ($parameter as $key => $value) {
            $alipayLoginUrl .= $key . "=" . $value . "&";
        }
        $alipayLoginUrl = substr($alipayLoginUrl, 0, count($alipayLoginUrl) - 2);
        return $alipayLoginUrl;
    }

    /**
     * 
     * 联合登录
     * @param array $unionLoginInfo		数据数组
     * @param string $redirectUrl		跳转地址
     */
    public function UnionLogin($unionLoginInfo, $redirectUrl) {
        $result = MemberDao::getUnionMember($unionLoginInfo["user_id"], $unionLoginInfo["aid"]);
        $memberResult = Handler_tool::dataTranslation($result);

        $logout_info = new Member_info();
        $logout_info->do_log_out();
        $logout_info->do_log_out_UnionLogin();

        if ($memberResult[0]["returns"] == 0) {
            $member = new Member_info($memberResult[0]["userName"], $memberResult[0]["passWord"]);
        }
        $unionLoginInfo = array('aid' => $unionLoginInfo["aid"],
            'uid' => $unionLoginInfo["user_id"],
            'uname' => $unionLoginInfo["user_name"],
            'isTemp' => $memberResult[0]["returns"],
            'isInitiative' => $unionLoginInfo["isInitiative"],
            'head_show' => $unionLoginInfo["head_show"],
            'jifen_url' => $unionLoginInfo["jifen_url"]
        );
        $memcacheKey = self::saveUnionLoginToCache($unionLoginInfo);
        $cookieKey = self::getUnionLoginCookieKey();
        Handler_http::setCookie($cookieKey, $memcacheKey, 0);
        Handler_tool::redirect($redirectUrl);
    }

    /**
     * 
     * 获取163联合登录配置
     */
    public static function getNeteaseLoginConfig() {
        return Union_Config::$Netease_Login;
    }

    /**
     * 
     * 获取163登录地址
     */
    public static function getNeteaseLoginUrl() {
        $netease_login_config = self::getNeteaseLoginConfig();
        $oauth_callback = HTTPURL . '/welcome/netease_login/'; //回调页面
        //生成参数数组
        $parameter = array('oauth_consumer_key' => $netease_login_config["KEY"],
            'oauth_nonce' => md5(time()),
            'oauth_signature_method' => $netease_login_config["SIGNMETHOD"],
            'oauth_timestamp' => time(),
            'oauth_version' => $netease_login_config["OAUTHVERSION"]
        );
        $parameterString = "?";
        foreach ($parameter as $key => $value) {
            $parameterString .= $key . "=" . $value . "&";
        }
        $parameterString = substr($parameterString, 0, count($parameterString) - 2);
        $parameterStringSign = substr($parameterString, 1);
        //拼接生成sign用的baseString
        $baseString = $netease_login_config["HTTPMETHOD"]
                . "&" . urlencode($netease_login_config["REQUESTTOKENURL"])
                . "&" . urlencode("oauth_callback=" . urlencode($oauth_callback))
                . urlencode("&" . $parameterStringSign);
        $sign = self::getNeteaseSign($baseString, "");
        //拼接URL 
        $neteaseURL = $netease_login_config["REQUESTTOKENURL"]
                . $parameterString
                . "&oauth_signature=" . urlencode($sign)
                . "&oauth_callback=" . urlencode($oauth_callback);
        $time_start = microtime(true);
        $result = file_get_contents($neteaseURL);
        $time_end = microtime(true);
        if (strpos($result, 'oauth_token') === false) {
            $msg .= "url: " . $neteaseURL . "\r\n";
            $time = ($time_end - $time_start) . "s\r\n";
            $msg .= "seconds: " . $time . "\r\n";
            $msg .= "result: " . $result . "\r\n";
            $msg .= "signString: " . $baseString . "\r\n";
            Log_File::writeWelcomeNeteaseLoginLog($msg);
            $neteaseLoginUrl = 'error';
        } else {
            parse_str($result, $RequestTokenArr);
            $memcacheKey = self::saveLoginSecretToCache($RequestTokenArr["oauth_token_secret"]);
            Handler_http::setCookie(Union_Config::$Netease_Login_Cookie_Key, $memcacheKey, 0);
            $neteaseLoginUrl = $netease_login_config["USERAUTHURL"] . "?oauth_token=" . $RequestTokenArr["oauth_token"];
        }
        if ($neteaseLoginUrl == 'error') {
            $neteaseLoginUrl = "javascript:location.reload();";
        }
        return $neteaseLoginUrl;
    }

    /**
     * 
     * 生成163的sign
     * @param string $baseString
     * @param string $oauthTokenSecret
     */
    public static function getNeteaseSign($baseString, $oauthTokenSecret) {
        $netease_login_config = self::getNeteaseLoginConfig();
        $sign = base64_encode(hash_hmac("sha1", $baseString, $netease_login_config["SECRET"] . "&" . $oauthTokenSecret, true));
        return $sign;
    }

    /**
     * 
     * 获取联合登录的Secret
     * @param string $key Secret
     */
    public static function getLoginSecret($key) {
        //从cookie中获取缓存key
        $key = Handler_http::getCookie($key);
        //不存在直接返回空字符串
        if (empty($key)) {
            return '';
        }
        //根据key从缓存中获取qq登录的信息
        $cache = MemoryCache::getInstance();
        $data = $cache->get($key);
        //不存在直接返回空字符串
        if (empty($data)) {
            return '';
        }
        return $data;
    }

    /**
     * 将联合登录登录的Secret存入Memcache，key由内部逻辑生成
     */
    public static function saveLoginSecretToCache($state) {
        $key = self::generateCacheKeyForUid($state);
        $cache = MemoryCache::getInstance();
        $cache->set($key, $state, 43200); //60*60*12
        return $key;
    }

    /**
     * 
     * 获取139联合登录配置
     */
    public static function getCMCCLoginConfig() {
        return Union_Config::$CMCC_Login;
    }

    /**
     * 
     * 获取139登录地址
     */
    public static function getCMCCLoginUrl() {
        $config = self::getCMCCLoginConfig();
        $srType = "0";
        $rUrl = HTTPURL . Union_Config::$CMCC_rUrl; //回调页面
        $rUrl = rawurlencode($rUrl);
        $rUrl = str_replace('%7E', '~', $rUrl);
        $timestamp = self::getCMCCTimestamp();
        $timestamp = $timestamp + 5 * 60;
        //拼串加密的的明文
        $sbMD5ProclaimedText = $config["CLICKSYSID"];
        $sbMD5ProclaimedText .= $srType;
        $sbMD5ProclaimedText .= $rUrl;
        $sbMD5ProclaimedText .= $timestamp;
        $sbMD5ProclaimedText .= $config["KEY"];
        //签名
        $smKey = strtoupper(md5($sbMD5ProclaimedText));

        $url = $config["SREDIRECT"]
                . "?clickSysId=" . $config["CLICKSYSID"]
                . "&rType=" . $srType
                . "&rUrl=" . $rUrl
                . "&mKey=" . $smKey
                . "&timestamp=" . $timestamp;
        return $url;
    }

    public static function getCMCCTimestamp() {
        $time_string = "2000-01-01";
        $year = ((int) substr($time_string, 0, 4)); //取得年份 
        $month = ((int) substr($time_string, 5, 2)); //取得月份 
        $day = ((int) substr($time_string, 8, 2)); //取得几号 
        $endtime = mktime(0, 0, 0, $month, $day, $year);
        $timestamp = time() - $endtime; //时间戳 后面的5*60=5分钟 表示期望在这个时间段内送达
        return $timestamp;
    }

    /**
     * 根据联合登录配置名称返回UID
     * @param string $union_name $Union_Login数组中union_name
     * @return Uid   | 	boolean false
     */
    public static function getUnionByUnionNameForUnionLogin($union_name) {
        foreach (Union_Config::$Union_Login as $uid => $arr) {
            if ($arr["union_name"] == $union_name) {
                return $uid;
            }
        }
        return false;
    }

    /**
     * 根据访问网站渠道,显示不同的400电话
     * @param <string> $UID union_id
     * @return String 400电话
     */
    public static function getUnionAccessPhoneNumber($UID) {
        $union_id = ucfirst(trim($UID));
        if (empty($union_id)) {
            $cookie_union = Handler_http::getCookie('union_id');
            if (empty($cookie_union)) {
                return SERVICE_TEL_400;
            }
            return self::find_phone_number($cookie_union);
        } else {
            if (strlen($union_id) == 8) {
                return self::find_phone_number($union_id);
            }
            return SERVICE_TEL_400;
        }
    }

    /**
     * 查找UID是否在数组中
     * @param <string> $UID
     * @return String 400电话
     */
    function find_phone_number($UID) {
        $sem_phone = Union_Config::$config_phone_400;
        foreach ($sem_phone as $key => $val) {
            if (in_array($UID, $val)) {
                return $key;
            }
            return SERVICE_TEL_400;
        }
    }

    /**
     * cpsRequest数据插入数据库
     * @param string $UnionId		union_id
     * @param string $OrderId		order_id
     * @param string $Type			类型
     * @param string $user_id   当前用户id
     * @param string $user_name
     */
    public static function insertCpsRequest($UnionId, $OrderId, $Type, $user_id, $user_name = "") {
        if (empty($UnionId) || empty($OrderId) || empty($Type) || !in_array($Type, array(1, 2)) || empty($user_id)) {
            return false;
        }

        $userInfo = array('user_id' => $user_id, 'user_name' => $user_name);

        $uids = explode('_', $UnionId);
        $union_id = $uids[0];
        $union_token = strtolower(union::getQueryTokenByUid($union_id));

        if (empty($union_token)) {
            //为空直接退出
            if (union::getUnionById($union_id)) {
                Log_File::writeCPSErrorLog('error: uid: ' . $union_id . ' union_token not found.');
            }
            return false;
        }

        if (!in_array($union_token, Union_Config::$sendRequestUnion)) {
//             Log_File::writeCPSErrorLog("error:union_token :{$union_token} not match,union_id :{$UnionId}");
            return false;
        }

        $getCookieFunName = 'getInfo_' . $union_token;
        $cookieValue = "";
        if (method_exists(Handler_union, $getCookieFunName)) {
            $cookieValue = self::$getCookieFunName();
        }

        $otherInfo = array();
        $otherInfo['QQUnionLogin'] = self::getUnionLoginInfo();
        //插入数据
        $_db = DB_MySQLi::getInstance();
        $sql = "INSERT INTO cps_request(UnionId,UnionToken,OrderId,Type,IsSent,CreateTime,UserInfo,CookieValue,OtherInfo)
		VALUES ('$UnionId', '$union_token', '$OrderId', $Type, 0, now(), '" . $_db->escapeString(json_encode($userInfo)) . "', '" . $_db->escapeString(base64_encode($cookieValue)) . "', '" . $_db->escapeString(json_encode($otherInfo)) . "')";
        try {
            $_db->query($sql);
        } catch (Exception $e) {
            Log_File::writeCPSErrorLog("sql:" . $sql . "/r/n error:" . $e);
        }

        return true;
    }

}

?>